﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace iPdf
{
    class SimpleActor : Actor
    {
        protected PdfReader reader;
        protected ActionItem workItem;

        protected string OwnerPassword
        {
            get
            {
                return workItem is PdfItem ? ((PdfItem)workItem).Password.Text : null;
            }
        }

        protected virtual void NullfyObjects()
        {
            reader = null;
        }

        protected virtual void ReadPdf(string fileName)
        {
            reader = new PdfReader(fileName);
        }

        protected void ReadPdf()
        {
            if (string.IsNullOrEmpty(OwnerPassword))
            {
                ReadPdf(workItem.Source);
            }
            else
            {
                reader = new PdfReader(workItem.Source, DocWriter.GetISOBytes(OwnerPassword));
            }
        }

        protected virtual void PreProcess() { }

        protected virtual void Manipulate() { }

        protected virtual void PostProcess() { }

        protected virtual void ClosePdf()
        {
            SharpHelper.ClosePdf(reader, null);
        }

        protected override void WorkOnItem(ActionItem item)
        {
            base.WorkOnItem(item);

            workItem = item;
            NullfyObjects();

            try
            {
                ReadPdf();
                PreProcess();
                Manipulate();
                ClosePdf();
                NullfyObjects();
                PostProcess();
            }
            finally
            {
                ClosePdf();
            }
        }

    }
}
